﻿//  @ Project : SPPager
//  @ File Name : HelperBase.cs
//  @ Date : 2013/6/9
//  @ Author : yubaolee(.cpp)
//  @ Description: 

using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Routing;

namespace LYB.NET.SPPager
{
    public abstract class HelperBase
    {
        protected readonly HtmlHelper _htmlHelper;
        protected readonly string _actionName;
        protected readonly string _controllerName;
        protected readonly int _totalPageCount = 1;
        protected readonly int _pageIndex;
        protected readonly int _startPageIndex = 1;
        protected readonly int _endPageIndex = 1;
        protected readonly PageOption _pageOption;
        protected const string _pageIndexJSPlaceholder = "PageIndexJSPlaceholder";
        protected string GoToPageScript = "<script type=\"text/javascript\">//<![CDATA[\r\n"
        + "function _LYBPage_GoToPage(_pib,_totalPageCount){"
        + "var pageIndex;"
        + "pageIndex=_pib.value;"
        + "var r=new RegExp(\"^\\\\s*(\\\\d+)\\\\s*$\");"
        + "if(!r.test(pageIndex)){alert(\"%InvalidPageIndexErrorMessage%\");return;}"
        + "else if(RegExp.$1<1||RegExp.$1>_totalPageCount){alert(\"%PageIndexOutOfRangeErrorMessage%\");return;}"
        + "var _hl=document.getElementById(_pib.id+'link').childNodes[1];"
        + "var _lh=_hl.href;_hl.href=_lh.replace('" + _pageIndexJSPlaceholder + "',pageIndex);"
        + "if(_hl.click){_hl.click();}"
        + "else{"
        + "var evt=document.createEvent('MouseEvents');"
        + "evt.initEvent('click',true,true);"
        + "_hl.dispatchEvent(evt);"
        + "}"
        + "_hl.href=_lh;}"
        + "\r\n//]]>\r\n</script>";

        public HelperBase(HtmlHelper helper, IPageList pagelist, PageOption pageoption)
        {
            if (pageoption == null)
                _pageOption = new PageOption();

            _htmlHelper = helper;
            _pageOption = pageoption;

            _actionName = (string)helper.ViewContext.RouteData.Values["action"];
            _controllerName = (string)helper.ViewContext.RouteData.Values["controller"];
            _pageIndex = pagelist.CurrentPageIndex;
            _totalPageCount = pagelist.TotalPageCount;

            // start page index
            _startPageIndex = _pageIndex - (pageoption.NumbericPagerItemCount / 2);
            if (_startPageIndex + pageoption.NumbericPagerItemCount > _totalPageCount)
                _startPageIndex = _totalPageCount + 1 - pageoption.NumbericPagerItemCount;
            if (_startPageIndex < 1)
                _startPageIndex = 1;

            // end page index
            _endPageIndex = _startPageIndex + pageoption.NumbericPagerItemCount - 1;
            if (_endPageIndex > _totalPageCount)
                _endPageIndex = _totalPageCount;

        }

        /// <summary>
        /// Generate url for page number
        /// </summary>
        protected string GenerateURL(int pagenumber)
        {
            //When the parameter is greater than total page number or equal to current page index,
            //there is no need to generate url
            if (pagenumber > _totalPageCount || pagenumber == _pageIndex)
                return null;

            var routeValues = GetCurrentRouteValue(_htmlHelper.ViewContext);

            //Set the URL parameter value in  Route Value. 
            //When pagenumber is zero,generate url link for javascript
            if (pagenumber == 0)
                routeValues["id"] = _pageIndexJSPlaceholder;
            else
                routeValues["id"] = pagenumber;

            var helper = new UrlHelper(_htmlHelper.ViewContext.RequestContext);
            return helper.RouteUrl(routeValues);
        }

        /// <summary>
        /// Get RouteValueDictionary(key-value pair) set of current URL 
        /// </summary>
        protected RouteValueDictionary GetCurrentRouteValue(ViewContext vc)
        {
            var routeValues = new RouteValueDictionary();
            var rq = vc.HttpContext.Request.QueryString;
            if (rq != null && rq.Count > 0)
            {
                var invalidParam = new[] { "x-requested-with", "xmlhttprequest", "id" };
                foreach (string key in rq.Keys)
                {
                    //remove parameter "id"
                    if (!string.IsNullOrEmpty(key) && Array.IndexOf(invalidParam, key.ToLower()) < 0)
                    {
                        routeValues[key] = rq[key];
                    }
                }
            }

            routeValues["action"] = _actionName;
            routeValues["controller"] = _controllerName;

            return routeValues;
        }

        //Pre page item
        protected void AddPrevious(ICollection<PagerItem> results)
        {
            var item = new PagerItem(_pageOption.PrevPageText, _pageIndex - 1, _pageIndex == 1, PagerItemType.PrevPage);
            if (!item.Disabled)
                results.Add(item);
        }

        //First page item
        protected void AddFirst(ICollection<PagerItem> results)
        {
            var item = new PagerItem(_pageOption.FirstPageText, 1, _pageIndex == 1, PagerItemType.FirstPage);
            if (!item.Disabled)
                results.Add(item);
        }

        //Next page item
        protected void AddNext(ICollection<PagerItem> results)
        {
            var item = new PagerItem(_pageOption.NextPageText, _pageIndex + 1, _pageIndex >= _totalPageCount, PagerItemType.NextPage);
            if (!item.Disabled)
                results.Add(item);
        }

        //Last page item
        protected void AddLast(ICollection<PagerItem> results)
        {
            var item = new PagerItem(_pageOption.LastPageText, _totalPageCount, _pageIndex >= _totalPageCount, PagerItemType.LastPage);
            if (!item.Disabled)
                results.Add(item);
        }

        //Page number item
        protected void AddPageNumbers(ICollection<PagerItem> results)
        {
            for (var pageIndex = _startPageIndex; pageIndex <= _endPageIndex; pageIndex++)
            {
                var text = pageIndex.ToString();
                if (pageIndex != _pageIndex)
                {
                    //different style
                }
                var item = new PagerItem(text, pageIndex, false, PagerItemType.NumericPage);
                results.Add(item);
            }
        }
    }
}
